package com.kavenka.zhufengfm.app.activity;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RadioGroup;
import com.kavenka.zhufengfm.app.R;
import com.kavenka.zhufengfm.app.fragments.CustomFragment;
import com.kavenka.zhufengfm.app.fragments.DiscoverFragment;
import com.kavenka.zhufengfm.app.fragments.DownloadFragment;
import com.kavenka.zhufengfm.app.fragments.PersonalFragment;

import java.util.LinkedList;
import java.util.List;


public class MainActivity extends ActionBarActivity implements RadioGroup.OnCheckedChangeListener {

    private List<Fragment> fragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFragments();
        initView();

    }
    private void initFragments() {
        if (fragments == null) {
            fragments = new LinkedList<Fragment>();
            fragments.add(new DiscoverFragment());
            fragments.add(new CustomFragment());
            fragments.add(new DownloadFragment());
            fragments.add(new PersonalFragment());
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            if (fragments.size() > 0) {
                for (Fragment fragment : fragments) {
                    transaction.add(R.id.main_fragment_container, fragment);
                    transaction.hide(fragment);
                }
                transaction.show(fragments.get(0));
            }
            transaction.commit();
        }
    }
    private void initView(){
        RadioGroup radioGroup= (RadioGroup) findViewById(R.id.main_radioGroup_tabBar);
        radioGroup.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int index=0;
        switch (checkedId){
            case R.id.main_radioBtn_discover:
                index=0;
                break;
            case R.id.main_radioBtn_custom:
                index=1;
                break;
            case R.id.main_radioBtn_download:
                index=2;
                break;
            case R.id.main_radioBtn_personal:
                index=3;
                break;
        }
        Fragment fragment = fragments.get(index);
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        for (int i = 0; i < fragments.size(); i++) {
            if (i!=index){
                transaction.hide(fragments.get(i));
            }else {
                transaction.show(fragments.get(i));
            }
        }
        transaction.commit();
    }
}
